<?php
class Login extends CI_Controller {
	public function __construct() {
		parent::__construct();
		$this->load->model('user_model');
        $this->load->model('user_remember_model');
	}
	
	public function do_login() {
		$data = array();
        $login_error_time = 0;
        if( $this->session->userdata('login_error_time') ) {
            $login_error_time = $this->session->userdata('login_error_time');
        }
        
		$ifExist = $this->user_model->exist($this->input->post('email'));
        $retJson = array();
		if ($ifExist === FALSE) {
            $retJson['code'] = 0;
            $retJson['html'] = '用户名或密码错误！';
            $this->session->set_userdata(array('login_error_time' => ++$login_error_time));
            if( $login_error_time >= 3 )
                $retJson['captchahtml'] = $this->load->view('login_captcha', '', true);
		} else {
			$res = $this->user_model->login($this->input->post());
			if ($res === TRUE) {
                $retJson['code'] = 1;
                $userinfo = $this->user_model->getUserInfo($this->input->post('email'));
                $remember = $this->input->post('remember');
                
                if ( $remember == 'true' && $userinfo['email_verified'] == 1 ) {
                    //选中记住密码，且用户已经验证过邮箱才能使用传说中的记住密码
                    $this->load->helper('cookie');
                    $saved_session = $this->user_remember_model->create_or_get_saved_session($this->input->post('email'));
                    
                    $session_cookie_email = array(
                        'name'   => 'REMEMBER_SESSION_EMAIL',
                        'value'  => $saved_session->email,
                        'expire' => '315360000',
                        'prefix' => 'EB_'
                    );
                    
                    $session_cookie_identify_token = array(
                        'name'   => 'REMEMBER_SESSION_ID_TOKEN',
                        'value'  => $saved_session->identify_token,
                        'expire' => '315360000',
                        'prefix' => 'EB_'
                    );
                    
                    $session_cookie_session_token = array(
                        'name'   => 'REMEMBER_SESSION_SESS_TOKEN',
                        'value'  => $saved_session->session_token,
                        'expire' => '315360000',
                        'prefix' => 'EB_'
                    );
                    
                    $this->input->set_cookie($session_cookie_email);
                    $this->input->set_cookie($session_cookie_identify_token);
                    $this->input->set_cookie($session_cookie_session_token);
                }
                
				$data['username'] = $this->input->post('email');                
                if ( $userinfo['email_verified'] == 1 ) {
                    $newdata = array(
                        'userinfo' => $userinfo
                    );
                }
                else {
                    //现在未验证用户等同视为访客，不给其正常用户权限了
                    $newdata = array(
                        'unverified_userinfo' => $userinfo
                    );
                }
                $this->session->set_userdata($newdata);
                $login_error_time = 0;
                $this->session->set_userdata(array('login_error_time' => 0));
                
                $html = '';
				// $html .= $this->load->view('header', $data, true);
				// $html .= $this->load->view('navbar', $data, true);
				// $html .= $this->load->view('home', $data, true);
				// $html .= $this->load->view('footer', $data, true);
                $retJson['html'] = $html;
			} else {
                $retJson['code'] = 0;
                $retJson['html'] = '用户名或密码错误！';
                $this->session->set_userdata(array('login_error_time' => ++$login_error_time));
                if( $login_error_time >= 3 )
                    $retJson['captchahtml'] = $this->load->view('login_captcha', '', true);
			}
		}
        $this->output->set_content_type('application/json')
                     ->set_output(json_encode($retJson));
	}
    
    public function do_cookie_login() {
        $data = array();
        $retJson = array();
        $this->load->helper('cookie');
        if ( $this->input->cookie('EB_REMEMBER_SESSION_EMAIL', TRUE) &&
                $this->input->cookie('EB_REMEMBER_SESSION_ID_TOKEN', TRUE) &&
                $this->input->cookie('EB_REMEMBER_SESSION_SESS_TOKEN', TRUE) ) {    //cookies中存在相关信息才予以登录
            $ifExist = $this->user_model->exist($this->input->cookie('EB_REMEMBER_SESSION_EMAIL', TRUE));
            if ($ifExist === FALSE) {
                $retJson['code'] = -1;       //返回-1，cookies中保存的email地址不存在（这很不正常），可能遭到了cookies欺骗之类的攻击
                $session_cookie_email = array(  //清除cookies防止隐患
                    'name'   => 'REMEMBER_SESSION_EMAIL',
                    'prefix' => 'EB_'
                );
                $session_cookie_identify_token = array(
                    'name'   => 'REMEMBER_SESSION_ID_TOKEN',
                    'prefix' => 'EB_'
                );
                $session_cookie_session_token = array(
                    'name'   => 'REMEMBER_SESSION_SESS_TOKEN',
                    'prefix' => 'EB_'
                );
                $this->load->helper('cookie');
                delete_cookie($session_cookie_email);
                delete_cookie($session_cookie_identify_token);
                delete_cookie($session_cookie_session_token);
            } else {
                $result = $this->user_remember_model->check_and_update_saved_session(
                        $this->input->cookie('EB_REMEMBER_SESSION_EMAIL', TRUE),
                        $this->input->cookie('EB_REMEMBER_SESSION_ID_TOKEN', TRUE),
                        $this->input->cookie('EB_REMEMBER_SESSION_SESS_TOKEN', TRUE)
                        );
                
                if ( $result >= 0 ) {
                    $retJson['code'] = 1;   //返回1，表示登录成功
                    
                    $userinfo = $this->user_model->getUserInfo($this->input->cookie('EB_REMEMBER_SESSION_EMAIL', TRUE));
                    $newdata = array(
                        'userinfo' => $userinfo
                    );
                    $this->session->set_userdata($newdata);
                }
                else {
                    $retJson['code'] = 0;   //返回0，登录失败，此处的原因是验证token失败，可能是IDtoken错误或者是SESStoken改变次数过多了。同样清除cookies防止隐患
                    $session_cookie_email = array(
                    'name'   => 'REMEMBER_SESSION_EMAIL',
                    'prefix' => 'EB_'
                    );
                    $session_cookie_identify_token = array(
                        'name'   => 'REMEMBER_SESSION_ID_TOKEN',
                        'prefix' => 'EB_'
                    );
                    $session_cookie_session_token = array(
                        'name'   => 'REMEMBER_SESSION_SESS_TOKEN',
                        'prefix' => 'EB_'
                    );
                    $this->load->helper('cookie');
                    delete_cookie($session_cookie_email);
                    delete_cookie($session_cookie_identify_token);
                    delete_cookie($session_cookie_session_token);
                }
            }
        }
        else {
            $retJson['code'] = 0;   //返回0，登录失败，此处的原因是cookies中没有相关信息
        }        
        $this->output->set_content_type('application/json')
                     ->set_output(json_encode($retJson));
    }
	
	public function modal() {
		$this->load->view('header');
		$this->load->view('login_modal');
		$this->load->view('footer');
	}
	
	public function logout() {        
		$this->session->sess_destroy();
        $session_cookie_email = array(
            'name'   => 'REMEMBER_SESSION_EMAIL',
            'prefix' => 'EB_'
        );
        $session_cookie_identify_token = array(
            'name'   => 'REMEMBER_SESSION_ID_TOKEN',
            'prefix' => 'EB_'
        );
        $session_cookie_session_token = array(
            'name'   => 'REMEMBER_SESSION_SESS_TOKEN',
            'prefix' => 'EB_'
        );
        $session_cookie_is_checked = array(
            'name'   => 'REMEMBER_SESSION_IS_CHECKED',
            'prefix' => 'EB_'
        );
        $session_cookie_show_optional_info_msg = array(
            'name'   => 'SHOW_OPTIONAL_INFO_MSG',
            'prefix' => 'EB_'
        );
        $this->load->helper('cookie');
        delete_cookie($session_cookie_email);
        delete_cookie($session_cookie_identify_token);
        delete_cookie($session_cookie_session_token);
        delete_cookie($session_cookie_is_checked);
        delete_cookie($session_cookie_show_optional_info_msg);
        redirect('');
	}
    
    public function is_login() {
        $is_login = $this->session->userdata('userinfo');
        if ($is_login === false) {
            echo FALSE;
        } else {
            echo TRUE;
        }
    }
}
?>